var unirest = require('unirest');
var request = require('request');
// var config = require('../config/config.json');
var config = require('../lib/config');
var moment = require('moment');
var logger = require('../lib/logger');
var _redis = require('../service/redis');
// 微信的服务类
// var token = null;
var jsapi_ticket = null;

exports.WechatService = function(){
  // 获取access_token
  this.getAccessToken = function(cb){
    _redis.get("wechat_access_token",function(err,resp){      
      var cache_token = JSON.parse(resp);
      logger.info(cache_token);
      if(cache_token == null || cache_token.expires_time < new Date().getTime()){
        var query = {};
        query.appid = config.wechat.appid;
        query.secret = config.wechat.appsecret;
        query.grant_type = "client_credential";
        logger.info(config.wechat.token_url);
        logger.info(query);
        unirest.get(config.wechat.token_url).query(query).end(function(response){
          var token = response.body;
          // 防止服务器时间的问题，提前10分钟就需要刷新
          if(token && token.expires_in > 0){
            token.expires_time = moment().add(token.expires_in - 600,'s').valueOf();
            _redis.set("wechat_access_token",JSON.stringify(token),function(err){
              return cb(null,token.access_token);
            })            
          }else{
            logger.error("can't get access_token from wechat...");
            logger.error(response.body);
            return cb("获取微信令牌失败");
          }        
        })
      }else{
        return cb(null,cache_token.access_token);
      }
    })
    
  };
  // 获取jsapi_ticket
  this.getJsapiTicket = function(cb){
    var that = this;
    _redis.get("wechat_jsapi_ticket",function(err,resp){
      var cache_jsapi_ticket = JSON.parse(resp);
      if(cache_jsapi_ticket == null ||  cache_jsapi_ticket.expires_time < new Date().getTime()){
        that.getAccessToken(function(err,access_token){
          if(err) return cb(err);
          var jsapi_ticket_url = config.wechat.jsapi_ticket_url;
          var params = {};
          var query = {};
          query.access_token = access_token;
          query.type = "jsapi";
          unirest.get(jsapi_ticket_url).query(query).end(function(response){
            var jsapi_ticket = response.body;
            if(jsapi_ticket && jsapi_ticket.expires_in > 0){
              jsapi_ticket.expires_time = moment().add(jsapi_ticket.expires_in - 600,'s').valueOf();
              _redis.set("wechat_jsapi_ticket",JSON.stringify(jsapi_ticket),function(err){
                logger.info(jsapi_ticket);
                return cb(null,jsapi_ticket.ticket);
              })
            }else{
              logger.error("can't get jsapi_ticket from wechat...");
              logger.error(response.body);
              return cb("获取jsapi_ticket失败");
            } 
          })
        })
      }else{
        return cb(null,cache_jsapi_ticket.ticket);
      }
    })    
  };
  // 发送模板消息
  this.sendTplMsg = function(tpl,openid,url,data,cb){
    var that = this;
    that.getAccessToken(function(err,access_token){
      if(err) return cb(err);
      var template_id = config.wechat[tpl];
      var tpl_url = config.wechat.tpl_send_url;
      var params = {};
      params.touser = openid;
      params.template_id = template_id;
      params.url = url;
      // params.data = data;
      params.data = {};
      for (key in data){
        params.data[key] = {};
        params.data[key]["value"] = data[key];
        params.data[key]["color"] = "#173177";
      }
      logger.info(params);
      unirest.post(tpl_url)
        .type('json')
        .query({"access_token":access_token})
        .send(params)
        .end(function(response){
          var result = response.body;
          if(result && result.errcode == 0){
            return cb(null);
          }else{            
            logger.error("can't send wechat template msg");
            logger.error(data);
            logger.error(result);
            return cb("发送模板消息失败");
          }
        })
    })    
  };
  this.getUserInfo = function(openid,cb){
    var that = this;
    that.getAccessToken(function(err,access_token){
      if(err){
        return cb(err);
      }
      var url = config.wechat.api_user_info;
      var query = {access_token:access_token,openid:openid};
      request.get({url:url,qs:query, json:true},function(err,response,body){
        if(err) return cb(err);
        var result = body;
        if(result && result.openid){
          return cb(null,result);
          // req.session.user.wx_no = openid;
          // req.session.user.wx_info = result;
          // return cb(null);
        }
        else{
          logger.error(body);
          // req.session.user.wx_info = null;
          return cb("无法找到用户信息");
        }
      })
     })
  };
  // 根据code获取token
  this.getAccessTokenByCode = function(code,cb){
    var that = this;
    var query = {};
    query.appid = config.wechat.appid;
    query.secret = config.wechat.appsecret;
    query.code = code;
    query.grant_type = 'authorization_code';
    request.get({url:config.wechat.user_token_url,qs:query,json:true},function(error, response, body){
      if(!body){
        logger.error("根据code获取token失败！！！");
        logger.error(error);
        logger.error(response);
        return cb("系统发生异常！")
      }
      if(body.errmsg){
        logger.error(body);
        return cb(body.errmsg);
      }
      if(body.openid){
        return cb(null,body);
      }else{
        logger.error(body);
        return cb("无法获取openid");
      }
     
    })
  }
}